<template>
  <div>
    <el-button
      type="primary"
      @click="changeStageType(0)"
      style="margin-bottom: 20px;"
      size="small"
    >添加阶段类型</el-button>

    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :show-close="false"
      :visible.sync="dialogVisible"
      width="500px"
      center
      @close="close()"
    >
      <el-form label-width="120px" :model="form" :rules="rules" ref="form" class="demo-ruleForm">
        <el-form-item label="类型名称" prop="stageName">
          <el-input v-model="form.stageName" placeholder="请输入阶段类型"></el-input>
        </el-form-item>
        <el-form-item label="关联职能组" prop="groupIds">
          <el-select v-model="form.groupIds" multiple placeholder="请选择职能组">
            <el-option
              v-for="item in functionGroupList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false;">取 消</el-button>
        <el-button type="primary" @click="save('form')" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>

    <BaseTable ref="baseTable" :tableSetting="tableSetting" @handleCommon="handleCommon" />
  </div>
</template>

<script>
import BaseTable from "../../../../components/table/baseTable";
import { selectFunctionGroupList } from "@/service/Api.js";
import {
  getStageList,
  addStageType,
  deleteStageType,
  editStageType,
} from "../../../../service/stageApi";

export default {
  name: "stageSetting",
  components: { BaseTable },
  data() {
    return {
      title: "",
      dialogVisible: false,
      loading: false,
      form: {
        stageName: "", //阶段类型名称
        stageId: "", //阶段类型id
        groupIds: [], //职能组id，多个之间用","隔开
        groupNames: "", //关联的职能组名称
      },
      rules: {
        stageName: [
          {
            required: true,
            message: "请输入类型名称",
            trigger: "blur",
          },
        ],
        groupIds: [
          {
            required: true,
            message: "请选择关联的职能组",
            trigger: "blur",
          },
        ],
      },
      stageType: [], //阶段类型列表
      functionGroupList: [], //职能组下拉列表
      options: [], //责任人下拉列表
      tableSetting: {
        tableApiFn: getStageList,
        options2: [
          {
            prop: "id",
            label: "id",
            isShow: false,
          },
          {
            prop: "stageName",
            label: "阶段类型",
            isShow: true,
          },
          {
            prop: "groupNames",
            label: "职能组",
            isShow: true,
          },
        ],
        btns: [
          {
            text: "编辑",
            size: "mini",
            handleName: "changeStageType",
            type: "primary",
            plain: "plain",
          },
          {
            text: "删除",
            size: "mini",
            handleName: "toDeleteStageType",
            type: "danger",
            plain: "plain",
          },
        ],
      },
      rowId: 0,
    };
  },
  created() {
    this.init();
  },
  methods: {
    //新增和编辑阶段类型共用一个弹框
    changeStageType(row) {
      //显示添加、修改阶段类型弹框
      if (row == 0) {
        this.title = "添加阶段类型";
        this.form = {};
      } else {
        console.log(row);

        this.form.groupNames = row.groupNames;
        console.log(this.form.groupNames);

        //需要先判断groupIds是否为字符串类型
        if (typeof row.groupIds === "string") {
          this.form.groupIds = row.groupIds
            .split(",")
            .map((elem) => Number(elem));
        }
        console.log(this.form.groupIds);

        this.title = "修改阶段类型";
        this.form.stageName = row.stageName;
        this.rowId = row.id;
      }
      this.dialogVisible = true;
    },
    close() {
      this.$refs["form"].resetFields();
      this.dialogVisible = false;
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //根据groupIds 查找对应的职能组名称
          var names = [];
          this.form.groupIds.forEach((el) => {
            this.functionGroupList.forEach((item) => {
              if (el == item.id) {
                names.push(item.name);
              }
            });
          });
          this.form.groupNames = names.join(",");
          console.log(this.form.groupNames);

          if (this.title == "添加阶段类型") {
            addStageType({
              stageName: this.form.stageName,
              groupIds: this.form.groupIds.join(","),
              groupNames: this.form.groupNames,
            }).then((res) => {
              if (res.code == 0) {
                this.$message.success("已成功添加阶段类型！");
                this.$refs.baseTable.initData();
                this.close();
              }
            });
          } else {
            editStageType({
              id: this.rowId,
              stageName: this.form.stageName,
              groupIds: this.form.groupIds.join(","),
              groupNames: this.form.groupNames,
            }).then((res) => {
              if (res.code == 0) {
                this.dialogVisible = false;
                this.$message.success("已成功修改阶段类型！");
                this.$refs.baseTable.initData();
              }
            });
          }
        } else {
          this.$message.error("阶段类型和职能组都不能为空！");
          return false;
        }
      });
    },
    toDeleteStageType(row) {
      //删除阶段类型
      this.$confirm("此操作将永久删除,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          deleteStageType(row.id).then((res) => {
            if (res.code === 0) {
              this.$message.success("删除成功!");
              this.$refs.baseTable.initData();
            } else {
              this.$message.warning(res.message);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleCommon(name, row, idx) {
      if (this[name]) {
        this[name](row, idx);
      }
    },
    //页面刚加载  初始化
    init() {
      let userInfo = sessionStorage.getItem("userInfo");
      let id = JSON.parse(userInfo).id;
      //获取阶段类型下拉列表
      getStageList().then((res) => {
        // console.log(res.data);
        this.stageType = res.data;
      });
      //获取职能组下拉列表
      selectFunctionGroupList(id).then((res) => {
        this.functionGroupList = res.data;
      });
    },
  },
};
</script>

<style scoped>
</style>